package base.thread;

import java.util.Random;

class ChopStick {
	String name;

	public ChopStick(String name) {
		this.name = name;
	}

	public String getChopStickName() {
		return name;
	}
}

class Philosopher extends Thread {

	String name;
	ChopStick leftChopStick;
	ChopStick rightChopStick;

	public Philosopher(String name, ChopStick leftChopStick,
			ChopStick rightChopStick) {
		this.name = name;
		this.leftChopStick = leftChopStick;
		this.rightChopStick = rightChopStick;
	}

	public String getPhilosopherName() {
		return name;
	}

	public void run() {
		try {
//			Thread.sleep(new Random().nextInt(10));

			synchronized (leftChopStick) {
				System.out.println(this.getPhilosopherName() + "  has "
						+ leftChopStick.getChopStickName()
						+ " and waiting for "
						+ rightChopStick.getChopStickName());
				Thread.sleep(new Random().nextInt(10));
				synchronized (rightChopStick) {
					System.out.println(this.getPhilosopherName()
							+ " begin eating");
				}
			}
		} catch (Exception e) {
		}
	}
}

public class PhilosopherTest {
	
	public static void main(String[] args) throws Exception {
		ChopStick chopStick1 = new ChopStick("chopStick1");
		ChopStick chopStick2 = new ChopStick("chopStick2");
		ChopStick chopStick3 = new ChopStick("chopStick3");
		ChopStick chopStick4 = new ChopStick("chopStick4");
		ChopStick chopStick5 = new ChopStick("chopStick5");

		Philosopher philosopher1 = new Philosopher("a", chopStick1, chopStick2);
		Philosopher philosopher2 = new Philosopher("b", chopStick2, chopStick3);
		Philosopher philosopher3 = new Philosopher("c", chopStick3, chopStick4);
		Philosopher philosopher4 = new Philosopher("d", chopStick4, chopStick5);
		Philosopher philosopher5 = new Philosopher("e", chopStick5, chopStick1);

		philosopher1.start();
		philosopher2.start();
		philosopher3.start();
		philosopher4.start();
		philosopher5.start();

		philosopher1.join();
		philosopher2.join();
		philosopher3.join();
		philosopher4.join();
		philosopher5.join();
		
		System.out.println("======over======");
	}
}
